<%--                                                                       --%>
<%-- Copyright (c) 2001-2003 BroadVision, Inc.  All rights reserved.       --%>
<%--                                                                       --%>
<%-- This software is copyrighted. Under the copyright laws, this software --%>
<%-- may not be copied, in whole or in part, without prior written consent --%>
<%-- of BroadVision, Inc. or its assignees. This software is provided      --%>
<%-- under the terms of a license between BroadVision and the recipient,   --%>
<%-- and its use is subject to the terms of that license.                  --%>
<%--                                                                       --%>
<%-- This software may be protected by one or more U.S. and International  --%>
<%-- patents.  Certain applications of BroadVision One-To-One software are --%>
<%-- covered by U.S. patent 5,710,887.                                     --%>
<%--                                                                       --%>
<%-- TRADEMARKS: BroadVision and BroadVision One-To-One are registered     --%>
<%-- trademarks of BroadVision, Inc., in the United States and the         --%>
<%-- European Community, and are trademarks of BroadVision, Inc., in other --%>
<%-- countries.  The BroadVision logo, is a trademark of BroadVision,      --%>
<%-- Inc., in the United States and other countries. Additionally, IONA    --%>
<%-- and Orbix are trademarks of IONA Technologies, Ltd.  RSA, MD5, and    --%>
<%-- RC2 are trademarks of RSA Data Security, Inc.                         --%>
<%--                                                                       --%>

<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ page import = "java.util.Locale" %>
<%@ page import = "java.util.Date" %>
<%@ page import = "java.util.Calendar" %> 
<%@ page import = "java.util.StringTokenizer" %>
<%@ page import = "java.text.DateFormat" %>
<%@ page import = "java.text.SimpleDateFormat" %>
<%@ page import = "java.text.FieldPosition" %>
<%@ page import = "javax.servlet.http.HttpSession" %>
<%@ page import = "org.apache.struts.Globals" %>
<%@ include file="/cs/common/charset.jsp" %>

<%!
  private Locale parseLocale(String locale) {
    Locale loc = null;
    if (null != locale) {
      String lang = null, country = null, variant = null;
      StringTokenizer tokens = new StringTokenizer(locale, "_");
      if (tokens.hasMoreTokens())
        lang = tokens.nextToken();
      if (tokens.hasMoreTokens())
        country = tokens.nextToken();
      if (tokens.hasMoreTokens())
        variant = tokens.nextToken();
      if (lang == null || lang.length() == 0) {
        // nothing
      }
      else if (country != null) {
        if (null != variant)
          loc = new Locale(lang, country, variant);
        else
          loc = new Locale(lang, country);
      }
      else {
        loc = new Locale(lang, "");
      }
    }
    return loc;
  }
%>
<%
String m = request.getParameter("m");
String d = request.getParameter("d");
String y = request.getParameter("y");
String form = request.getParameter("form");
String field = request.getParameter("field");
String minYear = request.getParameter("minYear");
String maxYear = request.getParameter("maxYear");
int minYr, maxYr;

HttpSession thisSession = request.getSession();
Locale locale = parseLocale(request.getParameter("locale"));
if (locale == null)
  locale = (Locale) thisSession.getAttribute(Globals.LOCALE_KEY);
if (locale == null)
  locale = Locale.getDefault();

SimpleDateFormat formatter = new SimpleDateFormat("MMMM", locale);
Date dummy = new Date();
dummy.setDate(1);  // initialize to the first of the month

Calendar c = Calendar.getInstance(locale);

if (m == null || m.equals("-1")) m = c.get(Calendar.MONTH) + "";
if (d == null || d.equals("-1")) d = c.get(Calendar.DATE) + "";
if (y == null || y.equals("-1")) y = c.get(Calendar.YEAR) + "";

try {
  minYr = Integer.parseInt(minYear);
}
catch (Exception ex) {
  minYr = c.get(Calendar.YEAR) - 10;
}
try {
  maxYr = Integer.parseInt(maxYear);
}
catch (Exception ex) {
  maxYr = c.get(Calendar.YEAR) + 10;
}
if (minYr > maxYr) {
  int tmp = minYr;
  minYr = maxYr;
  maxYr = minYr;
} 
String monthNames = "";
for (int monthIndex = 0; monthIndex < 12; monthIndex++) {
  dummy.setMonth(monthIndex);
  String monthName = formatter.format(dummy);
  monthNames = monthNames + ", '" + monthName + "'"; 
}
monthNames = monthNames.substring(2);

String[] weekdayNames = new String[7];

formatter = new SimpleDateFormat("EE", locale);
dummy.setMonth(0);   // 01/01/1995 = Sunday
dummy.setDate(1);
dummy.setYear(95);
for (int weekdayIndex = 0; weekdayIndex < 7; weekdayIndex++) {
  dummy.setDate(weekdayIndex+1);
  weekdayNames[weekdayIndex] = formatter.format(dummy);
}

DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
FieldPosition yearPosition = new FieldPosition(DateFormat.YEAR_FIELD);
FieldPosition monthPosition = new FieldPosition(DateFormat.MONTH_FIELD);
FieldPosition datePosition = new FieldPosition(DateFormat.DATE_FIELD);

StringBuffer yearBuf = new StringBuffer();
StringBuffer monthBuf = new StringBuffer();
StringBuffer dateBuf = new StringBuffer();

Date dtToday = new Date();

df.format(dtToday, yearBuf, yearPosition);
df.format(dtToday, monthBuf, monthPosition);
df.format(dtToday, dateBuf, datePosition);

int yPos = yearPosition.getBeginIndex();
int mPos = monthPosition.getBeginIndex();
int dPos = datePosition.getBeginIndex();

String dateOrder = "MDY";
if ((dPos < mPos) && (mPos < yPos)) dateOrder = "DMY";
else if ((yPos < mPos) && (mPos < dPos)) dateOrder = "YMD";
else if ((yPos < dPos) && (dPos < mPos)) dateOrder = "YDM";

%>

<html>
<head>
<title><bean:message bundle="appCommonRes"   key="cs.common.calendar.Title" /></title>
</head>
<style>
.theCalendar { position:absolute; }
</style>

<script language="JavaScript">

// array of the month names
var monthNames = new Array (<%= monthNames %>) ;

//
// Handle the event that a year or month has been selected from the dropdowns.
//
function onChange(m, d, y) {
  writeCalendar(m, d, y) ;
}

//
// The user has selected a date. Pass the date values back to
// the parent window's callback function 'setDate()'. And then
// close the popup window.
//
function setDate(y, m, d) {
  window.opener.setDate(y, m, d, '<%= form %>', '<%= field %>');
  window.close();
}

//
// Handle the event that the next or previous month arrow has been clicked.
//
function onMonth(month, day, year, dir, minYear, maxYear) {
  var m = month + dir;
  var y = year;

  if (m < 0) {
    m = 11;
    y-- ;
  }
  else if (m > 11) {
    m = 0;
    y++ ;
  }

  if (y < minYear)
    y = minYear;
  if (y > maxYear)
    y = maxYear;
  writeCalendar(m, day, y);
}

var calendarDiv ;

//
// Bring the popup window to the foreground when activated.
//
function onLoad() {
  focus();

  if (document.all) 
    calendarDiv = document.all.calendar;
  else if (document.layers)
    calendarDiv = document.layers['calendar'];
  else 
    calendarDiv = document.getElementById("calendar");

  writeCalendar(<%= m %>, <%= d %>, <%= y %>);
}

//
// Returns the number of days for the given month and year.
//
function getDaysInMonth(year, month) {
  var DaysInMonth = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
  var mi = month ;
  var result = DaysInMonth[mi];

  if (mi == 1) {
    if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
      result = 29;
    }
  }

  return result;
}

function navigateMonthUI(direction, m, d, y, minYear, maxYear) {
  var img = "arrow_left_blue.gif";
  if (direction == 1)
    img = "arrow_right_blue.gif";
  if (y < minYear || y > maxYear)
    return "";
  var projectedMonth = (direction ? m + 1 : m - 1);
  if (projectedMonth < 0 && y == minYear)
    return "";
  if (projectedMonth > 11 && y == maxYear)
    return ""; 
  return '<a href="javascript:onMonth(' + m + ', ' + d + ', ' + y + ', ' + (direction ? 1 : -1) + ', ' + minYear + ', ' + maxYear + ')"><img src="<%= request.getContextPath() %>/ca/images/icons/' + img + '" width=11 height=12 border=0 vspace=0 hspace=0></a>';
}

//
// Render a month view.
//
function writeCalendar(m, d, y) {
  var today = new Date;

  if (m == null) m = today.getMonth();
  if (d == null) d = today.getDate();
  if (y == null) y = today.getFullYear();

  var month = m;
  var year = y;

  var dt = new Date(year, month, 1);
  var weekDay = dt.getDay() ;

  var offset = (weekDay == 7) ? 0 : weekDay;
  var days = getDaysInMonth(year, month);
  var sum = days + offset;
  var rows = (sum / 7);

  var cursor = 0;
  var day = 1;
  var minYear = <%= minYr %>;
  var maxYear = <%= maxYr %>;

  var calHTML =
    "<form name=monthView>" +
    "<table cellpadding=0 cellspacing=0 border=0 bgcolor=#ffffff>" +
    "<tr>" +
      "<td align=center bgcolor=#dcdcdc>" +
      "<table cellpadding=0 cellspacing=1 border=0>" +
      "<tr bgcolor=#eeeeee>" +
        '<td align=center>' + navigateMonthUI(false, m, d, y, minYear, maxYear) + '</td>' +
<%
  if (dateOrder.equals("YMD") || dateOrder.equals("YDM")) {
%>
        '<td colspan=5 align=center><font face=verdana size=-2><b>' + y + '&nbsp;' + monthNames[m] + '</b></font></td>' +
<%
  } else {
%>
        '<td colspan=5 align=center><font face=verdana size=-2><b>' + monthNames[m] + '&nbsp;' + y + '</b></font></td>' +
<%
  }
%>
        '<td align=center>' + navigateMonthUI(true, m, d, y, minYear, maxYear) + '</td>' +
      "</tr>" +
      "<tr bgcolor=#dcdcdc>" +
        "<td align=center width=14%><font face=verdana size=-2><%= weekdayNames[0] %></font></td>" +
        "<td align=center width=14%><font face=verdana size=-2><%= weekdayNames[1] %></font></td>" +
        "<td align=center width=14%><font face=verdana size=-2><%= weekdayNames[2] %></font></td>" +
        "<td align=center width=14%><font face=verdana size=-2><%= weekdayNames[3] %></font></td>" +
        "<td align=center width=14%><font face=verdana size=-2><%= weekdayNames[4] %></font></td>" +
        "<td align=center width=14%><font face=verdana size=-2><%= weekdayNames[5] %></font></td>" +
        "<td align=center width=14%><font face=verdana size=-2><%= weekdayNames[6] %></font></td>" +
      "</tr>";

  for (var r = 0; r < rows; r++) {
    calHTML += '<tr bgcolor=#ffffff>';

    for (c = 0; c < 7; c++) {
      if (cursor < offset || day > days) {
        calHTML += '<td align=right>&nbsp;</td>';
      }
      else {
        calHTML += '<td height=25 align=right valign=top ' +
          (day == d ? 'bgColor="#eeeeee"' : '') + '><a href="#" onClick="setDate(' +
          year + ',' + month + ',' + day + ')"><font face=verdana size=-2>' +
          day + '</font></a></td>' ;
        day++;
      }

      cursor++;
    }

    calHTML += '</tr>' ;
  }

  calHTML += '<tr>' +
             '<td colspan=7>' +
             '<font face=verdana size=-2>';
<% 
  if (dateOrder.equals("YMD") || dateOrder.equals("YDM")) {
%>
    calHTML += '<select name="startYear" onChange="onChange(' + m +
               ', ' + d + ', this[selectedIndex].value)">' ;
    for (var i = minYear ; i <= maxYear; i++) {
      calHTML += '<option value=' + i + (y == i?' selected':'') + '>' + i + '</option>' ;
    }
    calHTML += "</select>";

    calHTML += '<select name="startMonth" onChange="onChange(Number(this[selectedIndex].value), ' + d + ', ' + y + ')">' ;

    for (var i = 0; i < monthNames.length; i++) {
      calHTML += '<option value=' + i + (m == i?' selected':'') + '>' + monthNames[i] + '</option>' ;
    }
    calHTML += '</select>';
<%
  } else {
%>
    calHTML += '<select name="startMonth" onChange="onChange(Number(this[selectedIndex].value), ' + d + ', ' + y + ')">' ;

    for (var i = 0; i < monthNames.length; i++) {
      calHTML += '<option value=' + i + (m == i?' selected':'') + '>' + monthNames[i] + '</option>' ;
    }
    calHTML += '</select>';

    calHTML += '<select name="startYear" onChange="onChange(' + m +
               ', ' + d + ', this[selectedIndex].value)">' ;
    for (var i = minYear ; i <= maxYear; i++) {
      calHTML += '<option value=' + i + (y == i?' selected':'') + '>' + i + '</option>' ;
    }
    calHTML += "</select>";
<%
  }
%>
  calHTML += "</font></td></tr>" +
             "</table>" +
             "</td>" +
             "</tr>" +
             "</table>" +
             "</form>" ;

  if (calendarDiv.innerHTML != null) {
    calendarDiv.innerHTML = calHTML ;
  }
  else {
    calendarDiv.document.open();
    calendarDiv.document.writeln(calHTML);
    calendarDiv.document.close();
  }
}

</script>

<body onLoad="onLoad()">
<div name="calendar" id="calendar" class="theCalendar">
</div>

</body>

</html>

